#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <functional>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_callback(wsserver_t* svr,websocketpp::connection_hdl hdl)
{
    //1、处理http请求
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    std::cout << "body:" << conn->get_request_body() << std::endl;
    websocketpp::http::parser::request req = conn->get_request();
    std::cout << "method:" << req.get_method() << std::endl;
    std::cout << "uri:" << req.get_uri() << std::endl;

    //2、构建并发送http应答给客户端
    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void open_callback(wsserver_t* svr,websocketpp::connection_hdl)
{
    std::cout << "websocket握手成功！" << std::endl;
}
void close_callback(wsserver_t* svr,websocketpp::connection_hdl)
{
    std::cout << "连接关闭！" << std::endl;
}
void message_callback(wsserver_t* svr,websocketpp::connection_hdl hdl,
                    wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    std::cout << "client say: " << msg->get_payload() << std::endl;
    std::string rep = "server say: " + msg->get_payload();
    conn->send(rep);
    
}

int main()
{
    //1、实例化server对象
    wsserver_t svr;
    //2、设置日志输出等级
    svr.set_access_channels(websocketpp::log::alevel::none);
    //3、初始化asio框架
    svr.init_asio();
    //4、设置业务处理回调函数
    svr.set_close_handler(std::bind(close_callback,&svr,std::placeholders::_1));
    svr.set_open_handler(std::bind(open_callback,&svr,std::placeholders::_1));
    svr.set_http_handler(std::bind(http_callback,&svr,std::placeholders::_1));
    svr.set_message_handler(std::bind(message_callback,&svr,std::placeholders::_1,std::placeholders::_2));
    //5、设置服务器监听端口
    svr.listen(8888);
    svr.set_reuse_addr(true);
    //6、开始获取新建连接
    svr.start_accept();
    svr.run();
    return 0;
}
